 
 $(document).ready(function() {
 	
 	var aud = $('#jukebox .aud').get(0);
 	aud.pos = -1;
  
  // Playback Event
  $('#jukebox .play').click(function(event) {
  	event.preventDefault();
  	
  	if (aud.pos < 0) {
  		$('#jukebox .next').trigger('click');
	  }
	  else {
	  	if(aud.paused == false) {
	  		aud.pause();
	  		$('#jukebox .controls a.play').css( 'background-image', 'url(css/img/play.png)');
    	}
    	else {
    		aud.play();
    		$('#jukebox .controls a.play').css( 'background-image', 'url(css/img/pause.png)');
    	}
    }
  })
  .mousedown(function() {
  	if(aud.paused == false) {
  		$('#jukebox .controls a.play').css( 'background-image', 'url(css/img/pause_press.png)');
  	}
  	else {
  		$('#jukebox .controls a.play').css( 'background-image', 'url(css/img/play_press.png)');
  	}
  })
  .mouseup(function() {
  	if(aud.paused == false) {
     $('#jukebox .controls a.play').css( 'background-image', 'url(css/img/pause.png)');
    }
    else {
     $('#jukebox .controls a.play').css( 'background-image', 'url(css/img/play.png)');
    }
  })
  .mouseout(function() {
  	if(aud.paused == false) {
     $('#jukebox .controls a.play').css( 'background-image', 'url(css/img/pause.png)');
    }	
    else {
     $('#jukebox .controls a.play').css( 'background-image', 'url(css/img/play.png)');
    }
  });
  
  // Stop Event
  $('#jukebox .stop').click(function(evt) {
  	evt.preventDefault();
  	aud.pause();
  	aud.currentTime = 0;
  	$('#jukebox .controls a.play').css( 'background-image', 'url(css/img/play.png)');
  	$('#jukebox .curTime').html("00:00");
  	$('#jukebox .totalTime').html("00:00");
  })
  .mousedown(function() {
  	$('#jukebox .controls a.stop').css( 'background-image', 'url(css/img/stop_press.png)');
  })
  .mouseup(function() {
  	$('#jukebox .controls a.stop').css( 'background-image', 'url(css/img/stop.png)');
  })
  .mouseout(function() {
  	$('#jukebox .controls a.stop').css( 'background-image', 'url(css/img/stop.png)');
  });
  
  // Next Event
  $('#jukebox .next').bind('click', function(evt) {
  	evt.preventDefault();
    	getNextAudioID();
  	
  	//aud.setAttribute('src', playlist[aud.pos].url);
  	//$('#jukebox .info').html(playlist[aud.pos].title);
  	//aud.load();
  })
  .mousedown(function() {
  	$('#jukebox .controls a.next').css( 'background-image', 'url(css/img/next_press.png)');
  })
  .mouseup(function() {
  	$('#jukebox .controls a.next').css( 'background-image', 'url(css/img/next.png)');
  })
  .mouseout(function() {
  	$('#jukebox .controls a.next').css( 'background-image', 'url(css/img/next.png)');
  });
  
  // Prev Event
  $('#jukebox .prev').click(function(evt) {
  	evt.preventDefault();
	getPrevAudioID();
  	
  	//if (aud.pos < 0) aud.pos = playlist.length - 1;
  	
  	//aud.setAttribute('src', playlist[aud.pos].url);
  	//$('#jukebox .info').html(playlist[aud.pos].title);
  	//aud.load();
  	$('#jukebox .curTime').html("00:00");
  	$('#jukebox .totalTime').html("00:00");  
  })
  .mousedown(function() {
  	$('#jukebox .controls a.prev').css( 'background-image', 'url(css/img/prev_press.png)');
  })
  .mouseup(function() {
  	$('#jukebox .controls a.prev').css( 'background-image', 'url(css/img/prev.png)');
  })
  .mouseout(function() {
  	$('#jukebox .controls a.prev').css( 'background-image', 'url(css/img/prev.png)');
  });
  
  // JQuery doesn't seem to like binding to these HTML 5
  // media events, but addEventListener does just fine
  
  aud.addEventListener('progress', function(evt) {
  	var width = parseInt($('#jukebox').css('width'));
  	var percentLoaded = Math.round(evt.loaded / evt.total * 100);
  	var barWidth = Math.ceil(percentLoaded * (width / 100));
  	$('#jukebox .load-progress').css( 'width', barWidth );
  });
  
  aud.addEventListener('timeupdate', function(evt) {
  	var width = parseInt($('#jukebox').css('width')); /* get */
  	var percentPlayed = Math.round(aud.currentTime / aud.duration * 100); /* integer closest to a */
  	var barWidth = Math.ceil(percentPlayed * (width / 100)); /* integer closest to a and not less than a */
  	$('#jukebox .play-progress').css( 'width', barWidth); /* set */
  	
  	var curtime = parseInt(aud.currentTime, 10);
  	var mins1 = Math.floor(curtime/60, 10);
  	var secs1 = curtime - mins1*60;
  	$('#jukebox .curTime').html((mins1 > 9 ? mins1 : '0' + mins1) + ":" + (secs1 > 9 ? secs1 : '0' + secs1));
  	
  	var totaltime = parseInt(aud.duration, 10);
  	var mins2 = Math.floor(totaltime/60, 10);
  	var secs2 = totaltime - mins2*60;
  	$('#jukebox .totalTime').html((mins2 > 9 ? mins2 : '0' + mins2) + ":" + (secs2 > 9 ? secs2 : '0' + secs2));
  });
  
  aud.addEventListener('canplay', function(evt) {
  	$('#jukebox .play').trigger('click');
  });
  
  aud.addEventListener('ended', function(evt) {
  	$('#jukebox .next').trigger('click');
  });
  
  /*$('#jukebox .info')[0].innerHTML(playlist[0].title);
  $('#jukebox .info').html("");*/
  $('#jukebox .curTime').html("00:00");
  $('#jukebox .totalTime').html("00:00");
  
  function getNextAudioID()
{
	var idStorage = parent.document.getElementById('input').getAttribute("idx");
	var db = openDatabase("html5playerDB", "1.0", "HTML5 Database API", 200000);
	
	db.transaction(function(tx) {
		//tx.executeSql("SELECT COUNT(*) FROM audio_playlist", [], function(result) {
			//db.transaction(function(tx) {
				tx.executeSql("SELECT _id, url, name, type, size FROM audio_playlist", [], function(tx, result) {
					for (var i = 0; i < result.rows.length; ++i) {
						
						var row = result.rows.item(i);
            var _id = row['_id'];
            var url = row['url'];
            var name = row['name'];
            var type = row['type'];
            var size = row['size'];
            
            if(_id == idStorage) {
            	var j = i+1;
            	if(j >= result.rows.length) {
            		var row1 = result.rows.item(0);
            		play(row1['_id']);
            		return;
            	}
            	else {
            		var row1 = result.rows.item(j);
            		play(row1['_id']);
            		return;
            	}
          	}
          }
          
        });
        
      //});
      
    //});
  });
}

function getPrevAudioID()
{
	var idStorage = parent.document.getElementById('input').getAttribute("idx");
	var db = openDatabase("html5playerDB", "1.0", "HTML5 Database API", 200000);
	
	db.transaction(function(tx) {
		//tx.executeSql("SELECT COUNT(*) FROM audio_playlist", [], function(result) {
			//db.transaction(function(tx) {
				tx.executeSql("SELECT _id, url, name, type, size FROM audio_playlist", [], function(tx, result) {
					for (var i = 0; i < result.rows.length; ++i) {
						
						var row = result.rows.item(i);
            var _id = row['_id'];
            var url = row['url'];
            var name = row['name'];
            var type = row['type'];
            var size = row['size'];
            
            if(_id == idStorage) {
            	var j = i-1;
            	if(j < 0) {
            		var row1 = result.rows.item(result.rows.length-1);
            		play(row1['_id']);
            		return;
            	}
            	else {
            		var row1 = result.rows.item(j);
            		play(row1['_id']);
            		return;
            	}
            }
          }
        });
        
      //});
      
    //});
  });
}
	
	function play(_id) {
		var db = openDatabase("html5playerDB", "1.0", "HTML5 Database API", 200000);
		db.transaction(function(tx) {
			tx.executeSql("SELECT url, name FROM audio_playlist where _id = ?", [_id], function(tx, result) {
				var row = result.rows.item(0);
				var path = row['url'];
				var name = row['name'];
				//var aud = parent.document.getElementById('jukebox_aud');
				aud.pause();
				aud.pos = _id;
				parent.document.getElementById('input').setAttribute("idx", _id);
				aud.setAttribute('src', path);
				aud.load();
				//$('#jukebox .info').html(name);
			});
		});
	} 
 });

//library DB 
function filesSelected(myFiles) {
	for (var i = 0, f; f = myFiles[i]; i++) {
		var audioReader = new FileReader();
		audioReader.onload = (function(aFile) {
			return function(e) {
				var typeStr = aFile.type;
				var nameStr = aFile.name;
				if(typeStr.substring(0, 5) == 'audio') {
    	  				insertNote(e.target.result, nameStr.substring(0,nameStr.lastIndexOf(".")), typeStr.substring(6).toUpperCase(), aFile.size);
				}
			};
    		})(f);
    		audioReader.readAsDataURL(f);
  	}
}


function insertNote(url, name, type, size) {
	var db = openDatabase("html5playerDB", "1.0", "HTML5 Database API", 200000);
	db.transaction(function(tx) {
		tx.executeSql("INSERT INTO audio (url, name, type, size) VALUES (?,?,?,?)", [url, name, type, size], function(result) {
			
			tx.executeSql("SELECT seq FROM sqlite_sequence where name = 'audio' ", [], function(tx, result) {
				
				var row = result.rows.item(0);
				var _id = row['seq'];
				var list = document.getElementById('iframeId').contentDocument.getElementById('list');
				var i = list.childNodes.length;
				
				var tr = document.createElement('tr');
				
				if(i%2 == 0) tr.setAttribute('class', 'even');
				else tr.setAttribute('class', 'odd');
					
				tr.setAttribute('id', 'id'+_id)
				tr.innerHTML = ['<td id="t1">&nbsp;<input type="checkbox" /></td>',
					'<td id="t2"> ', i+1,  ' </td>', 
					'<td id="t3">&nbsp;&nbsp; ', name, ' </td>', 
					'<td id="t4"> ', type, ' </td>',
					'<td id="t5"> ', size, ' </td>', 
					'<td id="t6"><input type="button" value=" X " onClick="delNote(', _id,')" /></td>',
					'<td id="t7"><input type="button" value=" > " onClick="addList(', _id,')" /></td>'].join('');
					list.insertBefore(tr, null);
      });
    		
    });
  });
}
//DB END



//playlist DB
function plistFileSelect(myFiles) {
  for (var i = 0, f; f = myFiles[i]; i++) {
    var audioReader = new FileReader();
    audioReader.onload = (function(aFile) {
      return function(e) {
    	  var typeStr = aFile.type;
    	  var nameStr = aFile.name;
    	  //alert( nameStr.substring(0,nameStr.lastIndexOf(".")) );
    	  if(typeStr.substring(0,5) == 'audio'){
    		  insertPlaylist(e.target.result, nameStr.substring(0,nameStr.lastIndexOf(".")), typeStr.substring(6).toUpperCase(), aFile.size);
    	  }
      };
    })(f);
    audioReader.readAsDataURL(f);
  }
}


function insertPlaylist(url, name, type, size)
{
	var db = openDatabase("html5playerDB", "1.0", "HTML5 Database API", 200000);
    db.transaction(function(tx) {
    	tx.executeSql("INSERT INTO audio_playlist (url, name, type, size) VALUES (?,?,?,?)", [url, name, type, size], function(result){
    		
    		tx.executeSql("SELECT seq FROM sqlite_sequence where name = 'audio_playlist' ", [], function(tx, result) {

    			var row = result.rows.item(0);
    			var _id = row['seq'];
    			
    			var list = document.getElementById('iframe_play_list').contentDocument.getElementById('playlist');
    			var i = list.childNodes.length;
    	     
                var tr = document.createElement('tr');
                if(i%2 == 0) tr.setAttribute('class', 'even');
                else tr.setAttribute('class', 'odd');
                		
                tr.setAttribute('id', 'id'+_id)
                tr.innerHTML = ['<td id="pl_t1">', i+1, '</td>', 
                            	'<td id="pl_t2" onclick="play(', _id, ')">', name, '</td>', 
                                '<td id="pl_t3"><input type="button" value=" X " onClick="delNote(', _id,')" /></td>'].join('');
                
                
                list.insertBefore(tr, null);
        	});
    		
    	});
    	
    });
}
//DB END

